package com.meida.module.bus.provider.service.impl;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.utils.DateUtils;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.entity.BusTestpaper;
import com.meida.module.bus.client.enums.TestPaperCheckStateEnum;
import com.meida.module.bus.provider.mapper.BusTestpaperMapper;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.bus.provider.service.BusTestpaperService;
import com.meida.module.marketing.client.entity.MkgCoupon;
import com.meida.module.marketing.client.entity.MkgCouponUser;
import com.meida.module.marketing.provider.service.CouponService;
import com.meida.module.marketing.provider.service.CouponUserService;
import com.meida.msg.client.entity.MsgReceive;
import com.meida.msg.provider.service.MsgReceiveService;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 试卷表接口实现类
 *
 * @author flyme
 * @date 2021-08-03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusTestpaperServiceImpl extends BaseServiceImpl<BusTestpaperMapper, BusTestpaper> implements BusTestpaperService {

    @Autowired
    private CouponService couponService;

    @Autowired
    private CouponUserService couponUserService;

    @Autowired
    private MsgReceiveService msgReceiveService;

    @Autowired
    private BusOrderService busOrderService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusTestpaper testpaper, EntityMap extra) {
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusTestpaper> cq, BusTestpaper testpaper, EntityMap requestMap) {
        cq.orderByDesc("testPaper.createTime");
        return ResultBody.ok();
    }

    @Override
    public ResultBody checkTestPaper(Long testpaperId, Integer state) {
        BusTestpaper busTestpaper = getById(testpaperId);
        busTestpaper.setState(state);
        boolean result = updateById(busTestpaper);
        if (result) {
            Long userId = busTestpaper.getUserId();
            String msgContent = "";
            //审核通过
            if (TestPaperCheckStateEnum.checkPass.getValue().equals(state)) {
                msgContent = "恭喜您！您的上传的试卷平台已审核通过！感谢您使用留同学APP";
                //从数据库随机抽取一种类型的优惠券进行赠送
                CriteriaQuery cq = new CriteriaQuery(MkgCoupon.class);
                cq.gt("surplusNum", 0);
                cq.last("order by rand() limit 1");
                MkgCoupon mkgCoupon = couponService.getOne(cq);
                Long couponId = mkgCoupon.getCouponId();
                RLock lock = redisLock.lock(couponId);
                try {
                    if (FlymeUtils.isNotEmpty(mkgCoupon)) {
                        //优惠券剩余库存量
                        Integer surplusNum = mkgCoupon.getSurplusNum();
                        if (surplusNum > 0) {
                            Integer validDays = FlymeUtils.getInteger(mkgCoupon.getValidDays(), 0);
                            MkgCouponUser mkgCouponUser = new MkgCouponUser();
                            mkgCouponUser.setUserId(userId);
                            mkgCouponUser.setCouponId(couponId);
                            mkgCouponUser.setUseState(0);
                            Date nowDate = DateUtils.getNowDate();
                            mkgCouponUser.setUserExpireBeginDate(nowDate);
                            Date endDate = DateUtils.plusDateDays(nowDate, validDays);
                            mkgCouponUser.setUserExpireEndDate(endDate);
                            mkgCouponUser.setIsDelete(0);
                            boolean save = couponUserService.save(mkgCouponUser);
                            if (save) {
                                mkgCoupon.setSurplusNum(surplusNum - 1);
                                couponService.updateById(mkgCoupon);
                            }
                        }
                    }
                } finally {
                    redisLock.unlock(lock);
                }
            } else {
                msgContent = "恭喜您！您的上传的试卷平台审核未通过！感谢您使用留同学APP";
            }
            String msgTitle = "试卷审核通知";
            MsgReceive msgReceive = msgReceiveService.sendMsgReceiveNotice(BusOrder.class.getSimpleName(), userId, msgTitle, msgContent);
            busOrderService.orderPushMessage(msgReceive, msgTitle, msgContent);
            return ResultBody.ok("审核操作成功");
        }
        return ResultBody.failed("审核操作失败");
    }
}
